﻿using Platformer_Example.Controller.Input;
using Platformer_Example.Controller.Terrain;
using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Helper;

namespace Platformer_Example.Controller.Character.Behavior
{
    public class WalkingBehavior : BaseAiBehavior
    {

        public override void LoadContent()
        {
            TakeActionIfServer(SetDirection);
            base.LoadContent();
        }

        void SetDirection()
        {
            if (Randomizer.Probability(0.5f))
            {
                Log.LogDebug("Walking computer decided to go left");
                Character.InputListener.KeyState[InputState.Key.Left] = true;
            }
            else
            {
                Log.LogDebug("Walking computer decided to go right");
                Character.InputListener.KeyState[InputState.Key.Right] = true;
            }
        }

        public override void UpdateWalkState(System.TimeSpan gameTime)
        {
            Character.ChangeDirectionFromInput();
            Character.ChangeWalkSpeedFromInput();

            Character.ApplyGravity(gameTime);

            var collisionX = Character.ApplyMovementX(gameTime);
            if (collisionX == BaseTerrain.TerrainType.Left || collisionX == BaseTerrain.TerrainType.Right)
            {
                //Change direction
                Character.InputListener.KeyState[InputState.Key.Right] = !Character.InputListener.KeyState[InputState.Key.Right];
                Character.InputListener.KeyState[InputState.Key.Left] = !Character.InputListener.KeyState[InputState.Key.Left];
            }
            if (Character.ApplyMovementY(gameTime, false) != BaseTerrain.TerrainType.Floor)
                Character.ChangeState(BaseInputCharacter.State.Fall);

            Character.ApplyWarps();
        }
    }
}